<?
class bjGateway{
   
    public static function executeAPI($output="JSON", $class="", $method="", $params)
    {
        //Check if a json parameter exists
        if(isset($_REQUEST["json"]) || isset($params["json"])){
             //Parse the json accordingly
             $params = json_decode(Util::nvl(@$_REQUEST["json"], $params["json"]));
        } else {
             $params = bjUtil::nvl($params, $_REQUEST);     
        }
   

        $filepath = sfConfig::get('sf_app_dir').DIRECTORY_SEPARATOR."lib".DIRECTORY_SEPARATOR.Util::nvl(@$_REQUEST["class"], $class).".class.php";          
        $out = "";
        if (file_exists ($filepath)){
            require_once($filepath);
            //Send the details
            $out = call_user_func(array(Util::nvl(@$_REQUEST["class"], $class), bjUtil::nvl(@$_REQUEST["method"], $method)), $params);
        } else {
            $out = array("msg" => "Could not find class name.", "success" => -1);      
        }

        //$out contains the output from that function
        //We need to check :output and extract accordingly
       
        $out["method"] = bjUtil::nvl(@$_REQUEST["method"], $method);
       
        $output = strtolower(bjUtil::nvl(@$_REQUEST["output"], $output));
       
        if($output == "phpserial"){
            echo serialize($out);     
        }
       
        if($output == "phparray"){
            return $out;     
        }
       
        if($output == "xml"){
            $xml = new XmlWriter();
            $xml->openMemory();
            $xml->startDocument('1.0', 'UTF-8');
            $xml->startElement('response');
            bjUtil::ArrayToXML($xml, $out);
            $xml->endElement();
            echo $xml->outputMemory(true);   
            return;         
        }       
       
        //special case for autocompletion
        if(bjUtil::nvl(@$_REQUEST["output"], $output) == "newline"){             
              return;
        }

        //Default to JSON output
        echo json_encode($out);     
    }   
}
?>